<script setup lang="ts">
// Element Plus 类型定义
interface FormInstance {
  validate: () => Promise<boolean>
  clearValidate: () => void
}

interface FormRules<T = any> {
  [key: string]: Array<{
    required?: boolean
    message?: string
    trigger?: string | string[]
    min?: number
    max?: number
  }>
}

// 定义店铺类型选项接口
interface StoreTypeOption {
  label: string
  value: string
}

// 定义人设接口
interface Persona {
  id: string
  name: string
  storeType: string
  createTime: string
  templates: number
  targets: number
  status: "published" | "unpublished"
  hasAvatarConfig: boolean
}

// 定义表单数据接口
interface FormData {
  storeType: string
  name: string
}

// 定义 Props
interface Props {
  visible: boolean
  persona?: Persona | null
  storeTypeOptions: StoreTypeOption[]
}

// 定义 Emits
interface Emits {
  (e: "update:visible", visible: boolean): void
  (e: "confirm", data: FormData): void
  (e: "cancel"): void
}

const props = withDefaults(defineProps<Props>(), {
  persona: null
})

const emit = defineEmits<Emits>()

// 表单引用
const formRef = ref<FormInstance>()

// 内部可见状态
const dialogVisible = computed({
  get: () => props.visible,
  set: (value: boolean) => emit("update:visible", value)
})

// 判断是否为编辑模式
const isEditMode = computed(() => !!props.persona)

// 弹窗标题
const dialogTitle = computed(() => {
  return isEditMode.value ? "编辑账号人设" : "新增账号人设"
})

// 按钮文字
const confirmButtonText = computed(() => {
  return isEditMode.value ? "更新" : "创建"
})

// 表单数据
const formData = ref<FormData>({
  storeType: "",
  name: ""
})

// 表单验证规则
const formRules: FormRules<FormData> = {
  storeType: [
    { required: true, message: "请选择店铺类型", trigger: "change" }
  ],
  name: [
    { required: true, message: "请输入人设名称", trigger: "blur" },
    { min: 2, max: 20, message: "人设名称长度应在2-20个字符之间", trigger: "blur" }
  ]
}

// 监听弹窗显示状态
watch(() => props.visible, (visible: boolean) => {
  if (visible) {
    // 弹窗打开时，如果是编辑模式则回填数据
    if (isEditMode.value && props.persona) {
      formData.value = {
        storeType: props.persona.storeType,
        name: props.persona.name
      }
    } else {
      // 新增模式，重置表单
      resetForm()
    }
  }
})

// 确认提交
async function handleConfirm() {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    emit("confirm", { ...formData.value })
  } catch (error) {
    console.log("表单验证失败:", error)
  }
}

// 取消操作
function handleCancel() {
  emit("cancel")
}

// 弹窗关闭时重置表单
function handleClosed() {
  resetForm()
}

// 重置表单
function resetForm() {
  formData.value = {
    storeType: "",
    name: ""
  }
  formRef.value?.clearValidate()
}
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="500px"
    :close-on-click-modal="true"
    :close-on-press-escape="true"
    @closed="handleClosed"
  >
    <div class="dialog-content">
      <div class="dialog-description">
        {{ isEditMode ? '修改账号人设信息' : '创建新的账号人设，可以为其配置专属的受众画像、推荐模板和对标账号。' }}
      </div>

      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        class="persona-form"
      >
        <el-form-item label="所属行业" prop="storeType">
          <el-select
            v-model="formData.storeType"
            placeholder="选择店铺类型"
            style="width: 100%"
          >
            <el-option
              v-for="option in storeTypeOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="人设名称" prop="name">
          <el-input
            v-model="formData.name"
            placeholder="如：专家型老板、搞笑测评员、邻家小姐姐"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm">
          {{ confirmButtonText }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.dialog-content {
  .dialog-description {
    margin-bottom: 24px;
    padding: 16px;
    background: #f8fafc;
    border-radius: 6px;
    font-size: 14px;
    color: #64748b;
    line-height: 1.5;
  }

  .persona-form {
    .el-form-item {
      margin-bottom: 20px;
    }

    :deep(.el-form-item__label) {
      color: #374151;
      font-weight: 500;
    }

    :deep(.el-input__wrapper) {
      border-radius: 6px;
    }

    :deep(.el-select) {
      .el-input__wrapper {
        border-radius: 6px;
      }
    }

    :deep(.el-input__count) {
      color: #9ca3af;
      font-size: 12px;
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;

  .el-button {
    min-width: 80px;
  }
}
</style>
